"use strict";

// Load plugins
const autoprefixer = require("gulp-autoprefixer");
const browsersync = require("browser-sync").create();
const cleanCSS = require("gulp-clean-css");
const del = require("del");
const gulp = require("gulp");
const header = require("gulp-header");
const merge = require("merge-stream");
const plumber = require("gulp-plumber");
const rename = require("gulp-rename");
const sass = require("gulp-sass");


// Load package.json for banner
const pkg = require('./package.json');


// BrowserSync reload
function browserSyncReload(done) {
  browsersync.reload();
  done();
}

// BrowserSync
function browserSync(done) {
  browsersync.init({
    server: {
      baseDir: "./"
    },
    port: 3000
  });
  done();
}

// Clean vendor
function clean() {
  return del(["./assets/css"]);
}


// Set the banner content
const banner = 
[ '/*\n',
  ' * Start layui2 - <%= pkg.name %> v<%= pkg.version %> (<%= pkg.homepage %>)\n',
  ' * Copyright 2019-' + (new Date()).getFullYear(), ' <%= pkg.author %>\n',
  ' */\n',
  '\n\n'
].join('');


// CSS task
function css() {
  return gulp
    .src("./assets/scss/**/*.scss")
    .pipe(plumber())
    .pipe(sass({
      outputStyle: "expanded",
      includePaths: "./node_modules",
    }))
    .on("error", sass.logError)
    .pipe(autoprefixer({
            //browsers: ['last 2 versions', 'Android >= 4.0'],
    				browsers: ['last 10 Chrome versions', 'last 5 Firefox versions', 'Safari >= 6', 'ie> 8'],
            cascade: false
        }))
    .pipe(header(banner, {
      pkg: pkg
    }))
    .pipe(gulp.dest("./assets/css"))
    .pipe(rename({
      suffix: ".min"
    }))
    .pipe(cleanCSS())
    .pipe(gulp.dest("./assets/css"))
    .pipe(browsersync.stream());
}



// Watch files
function watchFiles() {
  gulp.watch("./assets/scss/**/*.scss", css);
  gulp.watch("./**/*.html", browserSyncReload);
}


// Define complex tasks
const build  = gulp.series(clean, css);
const watch  = gulp.series(build, gulp.parallel(watchFiles, browserSync));


// Export tasks
exports.css = css;
exports.clean = clean;
exports.build = build;
exports.watch = watch;
exports.default = build;






